package com.dawn.seckilldemo.rabbit;

import cn.hutool.json.JSONUtil;
import com.dawn.seckilldemo.pojo.SeckillMessage;
import com.dawn.seckilldemo.pojo.SeckillOrder;
import com.dawn.seckilldemo.pojo.User;
import com.dawn.seckilldemo.service.GoodsService;
import com.dawn.seckilldemo.service.OrderService;
import com.dawn.seckilldemo.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class MQReceiverConsumer {
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderService orderService;

    //下单操作
    @RabbitListener(queues = "seckillQueue")
    public void queue(String message){
        log.info("接收到的消息："+message);
        SeckillMessage seckillMessage = JSONUtil.toBean(message, SeckillMessage.class);
        Long goodId = seckillMessage.getGoodId();
        User user = seckillMessage.getUser();
        //判断库存
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodId);
        if(goodsVo.getStockCount()<1){
            return;
        }
        //把订单和商品绑在一起存入redis中
        SeckillOrder o = (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodId);
        if(o !=null){
            return ;
        }
        //下单操作
        orderService.seckill(user,goodsVo);
    }
}
